Author: Hilko Bengen <bengen@debian.org>
Description: Escape user, vhost, uri, referer, agent strings in log.
Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=372536
---
This patch header follows DEP-3: http://dep.debian.net/deps/dep3/

--- a/urlsnarf.c
+++ b/urlsnarf.c
@@ -84,6 +84,43 @@
 	return (tstr);
 }
 
+static char *
+escape_log_entry(char *string)
+{
+	char *out;
+	unsigned char *c, *o;
+	size_t len;
+
+	if (!string)
+		return NULL;
+
+	/* Determine needed length */
+	for (c = string, len = 0; *c; c++) {
+		if ((*c < 32) || (*c >= 128))
+			len += 4;
+		else if ((*c == '"') || (*c =='\\'))
+			len += 2;
+		else
+			len++;
+	}
+	out = malloc(len+1);
+	if (!out)
+		return NULL;
+	for (c = string, o = out; *c; c++, o++) {
+		if ((*c < 32) || (*c >= 128)) {
+			snprintf(o, 5, "\\x%02x", *c);
+			o += 3;
+		} else if ((*c == '"') || ((*c =='\\'))) {
+			*(o++) = '\\';
+			*o = *c;
+		} else {
+			*o = *c;
+		}
+	}
+	out[len]='\0';
+	return out;
+}
+
 static int
 process_http_request(struct tuple4 *addr, u_char *data, int len)
 {
@@ -142,18 +179,26 @@
 				buf_tok(NULL, NULL, i);
 			}
 		}
-		if (user == NULL)
-			user = "-";
-		if (vhost == NULL)
-			vhost = libnet_addr2name4(addr->daddr, Opt_dns);
-		if (referer == NULL)
-			referer = "-";
-		if (agent == NULL)
-			agent = "-";
-		
+		user = escape_log_entry(user);
+		vhost = escape_log_entry(vhost);
+		uri = escape_log_entry(uri);
+		referer = escape_log_entry(referer);
+		agent = escape_log_entry(agent);
+
 		printf("%s - %s [%s] \"%s http://%s%s\" - - \"%s\" \"%s\"\n",
 		       libnet_addr2name4(addr->saddr, Opt_dns),
-		       user, timestamp(), req, vhost, uri, referer, agent);
+		       (user?user:"-"),
+		       timestamp(), req, 
+		       (vhost?vhost:libnet_addr2name4(addr->daddr, Opt_dns)), 
+		       uri,
+		       (referer?referer:"-"),
+		       (agent?agent:"-"));
+
+		free(user);
+		free(vhost);
+		free(uri);
+		free(referer);
+		free(agent);
 	}
 	fflush(stdout);
 	
